package com.java.netty.nio.netty.simple;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @Author: Dgg
 * @Date: 2021/12/12 21:35
 */
public class NettyClient {
	public static void main(String[] args) {
		//客户端需要一个事件循环组
		EventLoopGroup group = new NioEventLoopGroup();
		try {

			//创建客户端启动对象
			//注意客户端使用的不是ServerBootStrap 是 BootStrap
			Bootstrap bootstrap = new Bootstrap();

			//设置相关参数
			bootstrap.group(group)//设置线程
					.channel(NioSocketChannel.class)//设置客户端通道实现类（反射）
					.handler(new ChannelInitializer<SocketChannel>() {

						@Override
						protected void initChannel(SocketChannel socketChannel) throws Exception {
							socketChannel.pipeline().addLast(new NettyClientHandler());//加入自己的处理器
						}
					});
			System.out.println("client is okay");
			//启动客户端链接 服务器端
			//channelfutre 需要分析 涉及到neetty的异步模型
			ChannelFuture cf = bootstrap.connect("127.0.0.1", 6668).sync();
			//给cf 设置监听器 注册我们关心的事件
			cf.addListener(new ChannelFutureListener() {
				@Override
				public void operationComplete(ChannelFuture future) throws Exception {
					if (cf.isSuccess()) {
						System.out.println("监听端口成功");
					} else {
						System.out.println("监听端口失败");
					}
				}
			});
			//给关闭通道进行监听
			cf.channel().closeFuture().sync();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			group.shutdownGracefully();
		}


	}
}
